package com.gu.common.utils.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;

/**
 * @author Mr.Gu
 * @date 2020/10/13 10:42
 * @function :
 **/
public class AlibabaExcelUtil<T> {

    public static <T> List<T> readExcel(MultipartFile excel, Class cls) throws IOException {
        return readExcel(excel,cls,1);
    }

    public static <T> List<T> readExcel(MultipartFile excel,Class cls,int headRowNumber) throws IOException {
        return EasyExcelFactory.read(excel.getInputStream())
                .sheet()
                .headRowNumber(headRowNumber)
                .head(cls)
                .doReadSync();
    }

    public static void download(HttpServletResponse response, Class cls, List data, String fileName, String sheetName) throws Exception {
        download(response, cls, data, fileName, sheetName,null);
    }

    public static void download(HttpServletResponse response, Class cls, List data, String fileName, String sheetName, WriteHandler handler) throws Exception {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");

        //表头样式
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        //设置表头居中对齐
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //内容样式
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //设置内容靠左对齐
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

        ExcelWriterSheetBuilder builder = EasyExcel.write(response.getOutputStream(), cls)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet(sheetName)
                .registerWriteHandler(horizontalCellStyleStrategy);
        if(Objects.nonNull(handler)){
            builder.registerWriteHandler(handler);
        }
        builder.doWrite(data);
    }


}
